﻿using B.MESUI.Login.ProdManagement.Model;
using B.MESUI.Login.ProdManagement.Services;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace B.MESUI.Login.ProdManagement.From.排班
{
    public partial class GanttChartForm : DevExpress.XtraEditors.XtraForm
    {
        private List<GanttTask> _ganttTasks;

        public GanttChartForm()
        {
            InitializeComponent();
            InitializeGanttChart();
        }

        /// <summary>
        /// 初始化甘特图控件
        /// </summary>
        private void InitializeGanttChart()
        {
            schedulerControl1.Start = DateTime.Today;
            schedulerControl1.ActiveViewType = DevExpress.XtraScheduler.SchedulerViewType.Timeline;

            // 设置时间刻度（比如按天显示）
            var timelineView = schedulerControl1.Views.TimelineView;
            timelineView.Scales.Clear();
            timelineView.Scales.Add(new DevExpress.XtraScheduler.TimeScaleDay());

            // 你可以设置显示的时间区间
            // timelineView.TimelineScrollBarVisible = true; // 可选

            schedulerControl1.DataStorage.Appointments.DataSource = null;
            schedulerControl1.DataStorage.Resources.DataSource = null;
            LoadGanttData();

            schedulerControl1.CustomDrawAppointment += schedulerControl1_CustomDrawAppointment;
        }

        /// <summary>
        /// 加载甘特图数据
        /// </summary>
        private async void LoadGanttData()
        {
            try
            {
                // 显示加载状态
                ShowLoadingState(true);

                // 获取甘特图数据
                _ganttTasks = await WorkOrderService.GetGanttDataAsync();

                if (_ganttTasks != null && _ganttTasks.Count > 0)
                {
                    // 创建资源数据源（按产线分组）
                    var resources = _ganttTasks
        .Where(t => !string.IsNullOrEmpty(t.productioN_LINE))
        .Select(t => t.productioN_LINE)
        .Distinct()
        .Select((line, index) => new { Id = index + 1, Name = line })
        .ToList();

                    // 创建任务数据源

                    var appointments = _ganttTasks
      .Where(t => t.starT_TIME != DateTime.MinValue && t.enD_TIME != DateTime.MinValue)
      .Select(task => new AppointmentItem
      {
          codeid = task.codeid,
          starT_TIME = task.starT_TIME,
          enD_TIME = task.enD_TIME,
          workordeR_DESC = $"数量:{task.numbeR_COL} 进度:{task.procesS_PROGRESS ?? "0"}%",
          ResourceId = resources.FirstOrDefault(r => r.Name == task.productioN_LINE)?.Id ?? 1
      })
      .ToList();

                    // 1. 资源绑定
                    schedulerControl1.DataStorage.Resources.Mappings.Id = "Id";
                    schedulerControl1.DataStorage.Resources.Mappings.Caption = "Name";
                    schedulerControl1.DataStorage.Resources.DataSource = resources;

                    // 2. 任务绑定
                    schedulerControl1.DataStorage.Appointments.Mappings.Subject = "codeid";
                    schedulerControl1.DataStorage.Appointments.Mappings.Start = "starT_TIME";
                    schedulerControl1.DataStorage.Appointments.Mappings.End = "enD_TIME";
                    schedulerControl1.DataStorage.Appointments.Mappings.Description = "workordeR_DESC";
                    schedulerControl1.DataStorage.Appointments.Mappings.ResourceId = "ResourceId";
                    schedulerControl1.DataStorage.Appointments.DataSource = appointments;

                    // 设置视图
                    schedulerControl1.ActiveViewType = DevExpress.XtraScheduler.SchedulerViewType.Timeline;

                    // 调整时间范围
                    if (appointments.Count > 0)
                    {
                        var minDate = appointments.Min(a => a.starT_TIME);
                        var maxDate = appointments.Max(a => a.enD_TIME);
                        schedulerControl1.Start = minDate.Date;
                        // schedulerControl1.End = maxDate.Date.AddDays(1); // 可选
                    }

                    // 更新状态栏
                    UpdateStatusBar();
                }
                else
                {
                    MessageBox.Show("未找到工单数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载甘特图数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                ShowLoadingState(false);
            }
        }

        /// <summary>
        /// 显示加载状态
        /// </summary>
        /// <param name="isLoading">是否正在加载</param>
        private void ShowLoadingState(bool isLoading)
        {
            if (isLoading)
            {
                labelControlStatus.Text = "正在加载数据...";
                progressBarControl1.Visible = true;
            }
            else
            {
                labelControlStatus.Text = "就绪";
                progressBarControl1.Visible = false;
            }
        }

        /// <summary>
        /// 更新状态栏信息
        /// </summary>
        private void UpdateStatusBar()
        {
            if (_ganttTasks != null)
            {
                var totalTasks = _ganttTasks.Count;
                var totalQuantity = _ganttTasks.Sum(t => t.numbeR_COL);
                var productionLines = _ganttTasks.Where(t => !string.IsNullOrEmpty(t.productioN_LINE))
                                               .Select(t => t.productioN_LINE)
                                               .Distinct()
                                               .Count();

                labelControlStatus.Text = $"共 {totalTasks} 个工单，总数量 {totalQuantity}，涉及 {productionLines} 条产线";
            }
        }

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadGanttData();
        }

        /// <summary>
        /// 筛选按钮点击事件
        /// </summary>
        private void btnFilter_Click(object sender, EventArgs e)
        {
            ShowFilterDialog();
        }

        /// <summary>
        /// 显示筛选对话框
        /// </summary>
        private void ShowFilterDialog()
        {
            // 这里可以实现日期范围筛选等功能
            MessageBox.Show("筛选功能待实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ganttControl1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {

        }

        private void schedulerControl1_CustomDrawAppointment(object sender, DevExpress.XtraScheduler.CustomDrawObjectEventArgs e)
        {
            var appointmentViewInfo = e.ObjectInfo as DevExpress.XtraScheduler.Drawing.AppointmentViewInfo;
            if (appointmentViewInfo != null)
            {
                // 追加数量和进度
                string customText = $"{appointmentViewInfo.Appointment.Subject}\n{appointmentViewInfo.Appointment.Description}";
                var font = appointmentViewInfo.Appearance.Font;
                var brush = appointmentViewInfo.Appearance.GetForeBrush(e.Cache);
                var rect = (RectangleF)appointmentViewInfo.Bounds;

                e.Cache.DrawString(customText, font, brush, rect);
                e.Handled = true;
            }
        }

        private void schedulerControl1_Click(object sender, EventArgs e)
        {

        }
    }

    public class AppointmentItem
    {
        public string codeid { get; set; }
        public DateTime starT_TIME { get; set; }
        public DateTime enD_TIME { get; set; }
        public string workordeR_DESC { get; set; }
        public int ResourceId { get; set; }
    }
}